#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2020-06-05

@author: zhuyu
"""
import os
import time
import datetime
import xlwt
import baseFunc
import subprocess


def mkdir(logname):
    dirs = "/Users/wangjianwen/Documents/rkScreenshot/{}".format(logname)
    if not os.path.exists(dirs):
        os.makedirs(dirs)
    return dirs


def get_sysinfo(logname):
    # 实时获取相关信息
    dirpath = mkdir(logname +'/sysinfo')
    subprocess.Popen("adb logcat > {}/logcat.txt".format(dirpath), shell=True)
    time.sleep(2)
    os.popen("adb shell dumpsys meminfo >> {}/memInfo.txt".format(dirpath))
    os.popen("adb shell cat /proc/meminfo >> {}/procmemInfo.txt".format(dirpath))
    time.sleep(2)
    os.popen("adb shell top -m 100 -n 1 -s cpu >> {}/cpuInfo.txt".format(dirpath))
    subprocess.Popen("adb bugreport  >{}/bugreport.txt".format(dirpath), shell=True)
    time.sleep(1)
    # subprocess.Popen("adb shell dmesg -T  > {}/dmesg.txt".format(dirpath), shell=True)
    # time.sleep(1)


def pull_sysinfo(logname):
    dirpath = mkdir(logname)
    subprocess.Popen("adb root", shell=True)
    time.sleep(1)
    os.popen("adb pull /data/system/dropbox {}/dropbox".format(dirpath))
    os.popen("adb pull /data/anr {}/anr".format(dirpath))
    os.popen("adb pull /data/tombstones {}/tombstones".format(dirpath))
    os.popen("adb pull /sdcard/alipay/iotsdk/log {}/log".format(dirpath))


def screentshot(num):
    log_name = str(num) + '_{}'.format(baseFunc.gettime())
    baseFunc.screentshot(log_name)
    baseFunc.get_sysinfo(log_name)


def checkactivity(num):
    # windows = 'com.alipay.iot.xpaas/com.alipay.iot.xpaas.ui.CustomH5Activity' # 启动小程序的POS或GOLF
    windows = 'com.alipay.takengo/com.alipay.takengo.ui.ErrorActivity'
    wait_time = 240
    while True:
        lines = os.popen('adb shell dumpsys window | grep mCurrentFocu').readlines()
        if len(lines) == 0:
            time.sleep(1)
            wait_time -= 1
            continue
        ret_list = lines[0].split(' ')
        while '' in ret_list:
            ret_list.remove('')
        if windows == ret_list[-1][:-2]:
            print 'check start window success: ' + ret_list[-1][:-2]
            break
        elif wait_time <= 0:
            screentshot(num)
            print 'check start window fail: ' + ret_list[-1][:-2]
            break
        else:
            wait_time -= 1
            time.sleep(0.5)
            continue


def reboot_devices():
    num = 0
    i = 20
    book = xlwt.Workbook(encoding='utf-8')
    # 创建一个名为sheetname的表单
    sheet = book.add_sheet('restartData')
    try:
        while i:
            lines = os.popen("adb devices").readlines()
            sn = 'HMR011200527000304'
            for line in lines:
                if sn in line:
                    retime = time.strftime('%Y.%m.%d %H:%M:%S ', time.localtime(time.time()))
                    start_list = baseFunc.start_app()
                    # diff_set = set(baseFunc.GOLF_APP_LIST) - set(start_list) # golf或普通POS
                    diff_set = set(baseFunc.HUOGUI_APP_LIST) - set(start_list)
                    if len(diff_set) != 0:
                        print '开机启动app失败应用:{}'.format(','.join(diff_set))
                        log_name = '开机启动失败' + str(num) + '_{}'.format(baseFunc.gettime())
                        baseFunc.get_sysinfo(log_name)
                    print '{} ---第{}次重启---'.format(retime, num)
                    subprocess.Popen("adb reboot", shell=True)
                    begin_time = datetime.datetime.now()
                    # 等待设备启动成功，进入开机动画
                    time.sleep(40)
                    checkactivity(num)
                    end_time = datetime.datetime.now()
                    delta = int((end_time - begin_time).total_seconds() * 1000)
                    print '本次重启时长:{}'.format(delta)
                    sheet.write(num, 0, int(delta))
                    num = num + 1
            i -= 1
            time.sleep(0.5)
    finally:
        logname = '{}'.format(baseFunc.gettime())
        book.save('/Users/wangjianwen/Documents/rk3288Data/Huogui_restart_{}.xls'.format(logname))


if __name__ == "__main__":
    # 开机初始化，检查进程启动是否成功，检查启动后的界面是否符合预期
    reboot_devices()
    # checkactivity(1)
    # logname = '{}'.format(baseFunc.gettime())
    # pull_sysinfo(logname)

